
package com.kugou.game.sdk.ui.fragment;

import java.util.ArrayList;

import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Message;
import android.text.Html;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.kugou.game.sdk.api.common.ActivityOrientation;
import com.kugou.game.sdk.api.common.IEventCode;
import com.kugou.game.sdk.base.BaseSDKWorkerFragment;
import com.kugou.game.sdk.core.PayManager;
import com.kugou.game.sdk.core.PlatformEventDispatcher;
import com.kugou.game.sdk.core.SDKActions;
import com.kugou.game.sdk.core.SDKControler;
import com.kugou.game.sdk.core.UserManager;
import com.kugou.game.sdk.entity.Coupon;
import com.kugou.game.sdk.interfaces.OnRequestListener;
import com.kugou.game.sdk.statistics.StatCmd;
import com.kugou.game.sdk.statistics.StaticsManager;
import com.kugou.game.sdk.ui.dialog.CouponListDialog;
import com.kugou.game.sdk.ui.dialog.CouponListDialog.OnSelectOptionListener;
import com.kugou.game.sdk.ui.widget.LoadingView;
import com.kugou.game.sdk.utils.AppUtil;
import com.kugou.game.sdk.utils.Rx;
import com.kugou.game.sdk.utils.ToastUtil;

/**
 * 描述：充值fragment基类
 * 
 * @author wcj
 * @since 2014-11-25
 */
public abstract class BaseRechargeFragment extends BaseSDKWorkerFragment {

    public static interface OnEventListener {
        void onChangeRechargeMode();

        void onRechargeSuccess(int mode, int value);

        void onRechargeResultChange(boolean isChecking);

        void onCheckRechargeResult(String order, int value, int mode);
    }

    private static final int MSG_SHOW_LOADING_VIEW = 900;

    private static final int MSG_HIDE_LOADING_VIEW = 901;

    private static final int MSG_UPDATE_VIEW_BY_RATIO = 902;

    private static final int MSG_UPDATE_VIEW = 903;

    public static final int PADDING_BTN = 40;

    private TextView mChangeRechargeModeTv, mRecharegeCanGotKubiTextView;

    // 游币优惠信息布局
    private RelativeLayout mYoubiPreferentialLayout;

    private TextView mYoubiPreferentialInfoTV;

    private ImageView mYoubiPreferentialArrow;

    protected TextView mCommonTipsBarAccount;

    private OnEventListener mOnEventListener;

    private LoadingView mLoadingView;

    protected boolean mIsRechargeYoubi = false;

    // 用于优惠信息变化的时候更新界面
    private int mTempRechargeValue, mTempRechargeType;

    // 代金券相关
    protected Coupon mSelectedCoupon;

    protected RelativeLayout mCouponLayout, mCouponDatailLayout;

    private TextView mCouponStateTv, mCouponMoneyTv, mCouponDesc, mCouponLimitTimeTv,
            mCouponCloseTv;

    private ArrayList<Coupon> mCoupons;

    protected int mSelectedIndex = -1;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initCommonView();

    }

    @Override
    public void setupActions(ArrayList<String> actions) {
        super.setupActions(actions);
        actions.add(SDKActions.ACTION_YOUBI_RATIO_CHANGE);
    }

    @Override
    public void handleBroadcast(Context context, Intent intent) {
        super.handleBroadcast(context, intent);
        String action = intent.getAction();
        // 当游币充值优惠信息发生变化时，刷新界面
        if (action.equals(SDKActions.ACTION_YOUBI_RATIO_CHANGE)) {
            sendEmptyUiMessage(MSG_UPDATE_VIEW_BY_RATIO);
        }
    }

    public void setOnEventListener(OnEventListener onEventListener) {
        this.mOnEventListener = onEventListener;
    }

    public OnEventListener getOnEventListener() {
        return this.mOnEventListener;
    }

    private void initCommonView() {
        mCommonTipsBarAccount = (TextView) findViewById(Rx.id.kg_common_tips_bar_account_info);
        if (mCommonTipsBarAccount != null) {
            mCommonTipsBarAccount.setText(Html.fromHtml("<font color=#333333>当前账号："
                    + UserManager.getInstance().getCurrentUserName() + "</font>"));
        }

        mChangeRechargeModeTv = (TextView) findViewById(Rx.id.kg_common_tips_bar_other_mode);
        if (mChangeRechargeModeTv != null) {
            // 设置下划线
            mChangeRechargeModeTv.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
            // 设置抗锯齿
            mChangeRechargeModeTv.getPaint().setAntiAlias(true);
            mChangeRechargeModeTv.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (mOnEventListener != null) {
                        mOnEventListener.onChangeRechargeMode();
                    }
                }
            });
        }

        mLoadingView = (LoadingView) findViewById(Rx.id.kg_loadingView);

        ImageView redImageView = (ImageView) findViewById(Rx.id.kg_recharge_mode_red_round);
        if (!mIsRechargeYoubi && PayManager.hasYoubiRechargepreferential()
                && PayManager.isShowRedPoint() && redImageView != null) {
            redImageView.setVisibility(View.VISIBLE);
        }

        mRecharegeCanGotKubiTextView = (TextView) findViewById(Rx.id.kg_tv_recharge_can_get_youbi);
        if (mIsRechargeYoubi && mRecharegeCanGotKubiTextView != null) {
            mRecharegeCanGotKubiTextView.setVisibility(View.VISIBLE);
        }

        mYoubiPreferentialLayout = (RelativeLayout) findViewById(Rx.id.kg_rl_recharge_preferential);
        mYoubiPreferentialInfoTV = (TextView) findViewById(Rx.id.kg_tv_recharge_preferential_info);
        mYoubiPreferentialArrow = (ImageView) findViewById(Rx.id.kg_iv_arrow);
        TextView preferentialTitle = (TextView) findViewById(Rx.id.kg_recharge_preferential_title);
        if (mIsRechargeYoubi && PayManager.hasYoubiRechargepreferential()
                && mYoubiPreferentialLayout != null) {
            mYoubiPreferentialLayout.setVisibility(View.VISIBLE);
            preferentialTitle.setText(PayManager.getKubiRechargePreferentialSubTitle());
            mYoubiPreferentialInfoTV.setText(PayManager.getKubiRechargePreferentialDetail());
            mYoubiPreferentialLayout.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (mYoubiPreferentialInfoTV.getVisibility() == View.GONE) {
                        mYoubiPreferentialInfoTV.setVisibility(View.VISIBLE);
                        mYoubiPreferentialArrow.setImageResource(Rx.drawable.kg_blue_arrow_up);
                    } else {
                        mYoubiPreferentialInfoTV.setVisibility(View.GONE);
                        mYoubiPreferentialArrow.setImageResource(Rx.drawable.kg_blue_arrow_down);
                    }
                }
            });
        }
    }

    private void updateViewWhenYoubiRechargepreferentialChange() {
        if (mYoubiPreferentialLayout != null) {
            if (mIsRechargeYoubi && PayManager.hasYoubiRechargepreferential()) {
                mYoubiPreferentialLayout.setVisibility(View.VISIBLE);
            } else {
                mYoubiPreferentialLayout.setVisibility(View.GONE);
            }
        }

        updateCanGotKubiTextView(mTempRechargeValue, mTempRechargeType);
    }

    /**
     * 在游币充值的模式下，更新可获得的游币数
     * 
     * @param rechargeValue
     * @param rechargeType
     */
    public void updateCanGotKubiTextView(int rechargeValue, int rechargeType) {
        mTempRechargeType = rechargeType;
        mTempRechargeValue = rechargeValue;
        // 非游币充值，或者textview为空则不处理
        if (!mIsRechargeYoubi || mRecharegeCanGotKubiTextView == null) {
            return;
        }

        int tempValue = (int) (PayManager.getExchangeRatio(rechargeType, rechargeValue)
                * rechargeValue * PayManager.getYoubiRatio());

        if (PayManager.getExchangeKubiExtraNum(rechargeValue) > 0 && mSelectedCoupon == null) {
            mRecharegeCanGotKubiTextView.setText(Html.fromHtml("<font color=#333333>可获得游币数："
                    + tempValue + "游币" + "</font>" + "<font color=#fd9526>+"
                    + PayManager.getExchangeKubiExtraNum(rechargeValue) + "游币" + "</font>"));
        } else {
            mRecharegeCanGotKubiTextView.setText(Html.fromHtml("<font color=#333333>可获得游币数："
                    + tempValue + "游币" + "</font>"));
        }
    }

    public void showLoadingView(String info) {
        Message msg = Message.obtain();
        msg.what = MSG_SHOW_LOADING_VIEW;
        msg.obj = info;
        sendUiMessage(msg);
    }

    public void showLoadingView() {
        sendEmptyUiMessage(MSG_SHOW_LOADING_VIEW);
    }

    public void hideLoadingView() {
        sendEmptyUiMessage(MSG_HIDE_LOADING_VIEW);
    }

    @Override
    public void handleUiMessage(Message msg) {
        if (getActivity() == null || getActivity().isFinishing() || isDetached() || !isAdded()) {
            return;
        }

        switch (msg.what) {
            case MSG_SHOW_LOADING_VIEW:
                if (mLoadingView != null) {
                    mLoadingView.setVisibility(View.VISIBLE);
                    mLoadingView.setText("充值中，请稍候");
                    if (msg.obj != null) {
                        mLoadingView.setText((String) msg.obj);
                    }
                }
                break;
            case MSG_HIDE_LOADING_VIEW:
                if (mLoadingView != null) {
                    mLoadingView.setVisibility(View.GONE);
                }
                break;
            case MSG_UPDATE_VIEW_BY_RATIO:
                updateViewWhenYoubiRechargepreferentialChange();
                break;

            case MSG_UPDATE_VIEW:
                updateView();
                break;
            default:
                break;
        }
    }

    /**
     * 发送充值成功事件
     * 
     * @param orderId
     * @param mode
     * @param orderValue
     */
    protected void sendRechargeSuccessEvent(String orderId, int mode, int orderValue) {
        Bundle chargeData = new Bundle();
        chargeData.putString("orderid", orderId);
        chargeData.putInt("optype", mIsRechargeYoubi ? 1 : 2);
        chargeData.putInt("paytype", mode);
        chargeData.putInt("paymoney", orderValue);
        PlatformEventDispatcher.sendEvent(IEventCode.RECHARGE_SUCCESS, chargeData);
    }

    /**
     * 发送统计-点击确认支付按钮
     * 
     * @param mode
     * @param payValue
     */
    protected void sendClickConfirmRechargeBtnStatics(int mode, int payValue) {
        StaticsManager.sendClickRechargeStatics(mIsRechargeYoubi ? 1 : 2, mode, payValue);
    }

    /**
     * 发送统计-取消支付|支付错误
     */
    protected void sendCancelRechargeStatics(int mode, int payValue, String orderid,
            int recordtype, String errormsg) {
        StaticsManager.sendCancelRechargeStatics(recordtype == 0 ? StatCmd.CMD_RECHARGE_CANCEL
                : StatCmd.CMD_RECHARGE_ERROR, mIsRechargeYoubi ? 1 : 2, mode, payValue, orderid,
                errormsg);
    }

    /**
     * 初始化代金券界面
     */
    protected void initCoupon() {

        mCouponLayout = (RelativeLayout) findViewById(Rx.id.kg_layout_coupon);
        mCouponLayout.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (PayManager.isCouponInfosRequestFailed()
                        && PayManager.getCouponInfos(mIsRechargeYoubi) == null) {
                    PayManager.requestCouponInfo(mIsRechargeYoubi, new OnRequestListener() {

                        @Override
                        public void onSuccess() {
                            sendEmptyUiMessage(MSG_UPDATE_VIEW);
                        }

                        @Override
                        public void onFailed(String errorMsg) {
                            ToastUtil.showMsg(errorMsg);
                        }
                    });
                    ToastUtil.showMsg("加载代金券信息");
                } else {
                    showCouponList();
                }
            }
        });

        mCouponDatailLayout = (RelativeLayout) findViewById(Rx.id.kg_layout_coupon_item);
        mCouponStateTv = (TextView) findViewById(Rx.id.kg_tv_coupon_state);
        mCouponMoneyTv = (TextView) findViewById(Rx.id.kg_tv_coupon_money);
        mCouponDesc = (TextView) findViewById(Rx.id.kg_tv_coupon_desc);
        mCouponLimitTimeTv = (TextView) findViewById(Rx.id.kg_tv_coupon_time);
        mCouponCloseTv = (TextView) findViewById(Rx.id.kg_tv_close_coupon);

        // 游币充值并且有活动的情况下显示提醒活动和代金券只能选一
        if (mIsRechargeYoubi && PayManager.hasYoubiRechargepreferential()) {
            findViewById(Rx.id.kg_coupon_notice).setVisibility(View.VISIBLE);
        }

        mCouponCloseTv.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                mSelectedIndex = -1;
                mSelectedCoupon = null;
                sendEmptyUiMessage(MSG_UPDATE_VIEW);
                updateFixedMoneyNumTextView();
            }
        });
    }

    /**
     * 更新界面，子类实现
     */
    protected void updateView() {
    }

    /**
     * 更新代金券UI
     * 
     * @param value
     */
    public void updateCouponView(int value) {
        mCoupons = PayManager.getCouponInfos(mIsRechargeYoubi, value);
        ArrayList<Coupon> allCoupons = PayManager.getCouponInfos(mIsRechargeYoubi);

        // 选择金额不符合已选中代金券，则去掉选中代金券
        if (mSelectedCoupon != null && value < mSelectedCoupon.getMoneyLimit()) {
            mSelectedCoupon = null;
            mSelectedIndex = -1;
        }

        if (mSelectedCoupon != null) { // 有选中代金券状态
            mCouponLayout.setVisibility(View.VISIBLE);
            if (SDKControler.getActivityOrientation() == ActivityOrientation.LANDSCAPE) {
                mCouponLayout.setBackgroundResource(Rx.drawable.kg_coupon_item_land);
            } else {
                mCouponLayout.setBackgroundResource(Rx.drawable.kg_coupon_item_selected);
            }
            mCouponStateTv.setText(Html.fromHtml("<font color=#666666>代金券：</font>"
                    + "<font color=#fc5f28>" + mCoupons.size() + "张可用</font>"));
            mCouponLayout.setEnabled(true);
            mCouponDatailLayout.setVisibility(View.VISIBLE);
            mCouponMoneyTv.setText("" + mSelectedCoupon.getMoney());
            mCouponDesc.setText(mSelectedCoupon.getCouponName());

            if (mSelectedCoupon.getLockStatus() == Coupon.COUPON_STATUS_LOCK) {
                mCouponLimitTimeTv.setText(AppUtil.getDate("订单提交中，HH时mm分",
                        mSelectedCoupon.getLockTime())
                        + "后可用");
            } else {
                mCouponLimitTimeTv.setText("截止期"
                        + AppUtil.getDate("yyyy.MM.dd", mSelectedCoupon.getEndtime()));
            }
        } else if (allCoupons == null && !PayManager.isCouponInfosRequestFailed()
                && !mIsRechargeYoubi) { // 普通充值，没有代金券情况，不显示
            mCouponLayout.setVisibility(View.GONE);
        } else if (allCoupons == null && PayManager.isCouponInfosRequestFailed()) { // 加载失败情况
            mCouponLayout.setVisibility(View.VISIBLE);
            mCouponDatailLayout.setVisibility(View.GONE);
            mCouponLayout.setBackgroundResource(Rx.drawable.kg_coupon_no_data);
            mCouponStateTv.setText(Html.fromHtml("<font color=#333333>代金券信息加载失败，</font>"
                    + "<font color=#479dfc><u>请点击重新加载</u></font>"));
            mCouponLayout.setEnabled(true);
        } else if ((mCoupons == null || mCoupons.size() == 0)
                && !PayManager.isCouponInfosRequestFailed()) { // 网络没问题情况，没有可用代金券
            mCouponLayout.setVisibility(View.VISIBLE);
            mCouponDatailLayout.setVisibility(View.GONE);
            mCouponLayout.setBackgroundResource(Rx.drawable.kg_coupon_no_data);
            mCouponStateTv.setText("代金券：无可用代金券");
            mCouponLayout.setEnabled(false);
        } else if (mCoupons != null) { // 有可用代金券
            mCouponLayout.setVisibility(View.VISIBLE);
            mCouponDatailLayout.setVisibility(View.GONE);

            mCouponLayout.setBackgroundResource(Rx.drawable.kg_coupon_normal);
            mCouponStateTv.setText(Html.fromHtml("<font color=#333333>代金券：</font>"
                    + "<font color=#fc5f28>" + mCoupons.size() + "张可用</font>"));
            mCouponLayout.setEnabled(true);
        }
    }

    private void showCouponList() {
        CouponListDialog dialog = new CouponListDialog(getActivity());

        dialog.setCurrentOptionIndex(mSelectedIndex);
        dialog.setDialogTitle("请选择代金券");
        dialog.addDatas(mCoupons);

        dialog.setOnSelectOptionListener(new OnSelectOptionListener() {

            @Override
            public void onSelectedItem(Coupon option, int index) {
                mSelectedIndex = index;
                mSelectedCoupon = option;
                sendEmptyUiMessage(MSG_UPDATE_VIEW);
                updateFixedMoneyNumTextView();
            }

            @Override
            public void onCancelItem(Coupon option, int index) {

                // if (option.getId() == mSelectedCoupon.getId()) {
                // mSelectedCoupon = null;
                // mSelectIndex = -1;
                // updateView();
                // updateFixedMoneyNumTextView();
                // }

            }
        });
        dialog.show();
    }

    public void canelRecharge() {
        mSelectedCoupon = null;
        mSelectedIndex = -1;
        sendEmptyUiMessage(MSG_UPDATE_VIEW);

        PayManager.requestCouponInfo(mIsRechargeYoubi, new OnRequestListener() {

            @Override
            public void onSuccess() {
                sendEmptyUiMessage(MSG_UPDATE_VIEW);
            }

            @Override
            public void onFailed(String errorMsg) {
                ToastUtil.showMsg(errorMsg);
            }
        });
    }

    protected void updateFixedMoneyNumTextView() {
    }

}
